const fs = require('fs');
const path = require('path');

const Cart = require('./cart');

const p = path.join(path.dirname(process.mainModule.filename), 'data', 'products.json');

const getProductFormFile = (cb) =>{
   
    fs.readFile(p, (err, fillcontent)=>{
        if(err){
            return cb([]);
        }
        cb(JSON.parse(fillcontent))
    })
}
module.exports = class Product {
    constructor(id, title, imageUrl, price, description){
      this.id = id;
      this.title = title;
      this.imageUrl = imageUrl;

      this.price = price;

      this.description = description;

    }
    save(){
        getProductFormFile(products =>{
            if(this.id){
                const existingProductIndex = products.findIndex(prod=> prod.id === this.id);
                const updateProducts =[...products];
                updateProducts[existingProductIndex] = this;
                fs.writeFile(p, JSON.stringify(updateProducts), err=>{
                    console.log(err)
                })

            }
            this.id = Math.random().toString();

            products.push(this);
            fs.writeFile(p, JSON.stringify(products), err=>{
                 console.log(err)
             })
        })
    }
    //在类上可以直接执行时 定义为静态方法
    static fetchAll(cb){
        getProductFormFile(cb)
    }
  //删除产品所需Id
  static deleteById(id){
    getProductFormFile(products =>{
        const product = products.find(p => p.id === id);
        const updateProducts = products.filter(p => p.id !== id);
        fs.writeFile(p, JSON.stringify(updateProducts), err=>{
            if(!err) {
                Cart.deleteById(id, product.price);
            }
        })
    
    })
  }
    static findById(id, cb){
        getProductFormFile(products =>{
            const product = products.find(p => p.id === id)
            cb(product);
        })


    }
}